import React, {Component} from 'react';
import './index.less';
import {
    base,
    toast,
    promptBox,
    print,
    output,
} from 'nc-lightapp-front';


import ReferSearch from 'src/hrpub/common/components/referSearch/org';
import NCBackBtn from 'src/hrpub/common/components/hr-back';
import do_print from 'src/hrpub/common/utils/print';
import Export from 'src/hrpub/common/utils/exportHtml'
import ContractTextViewAction from "./functions/ContractTextViewAction";
import BrowseTempletAction
    from "../../../../basicsetting/templet_base/main/components/Header/functions/BrowseTempletAction";
import updateButtonStatus from "./functions/updateButtonStatus";
import MakeCenterAction from "./functions/MakeCenterAction";
import isMac from "../../../../public/functions/isMac";
import {nodeRefs} from '../../main/common';
const {NCCheckbox} = base;
const tableid = 'psninfo';

class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json: props.json,
            hrorgobj: {}, //人力资源组织
            isBtnFirst: true  //是否是按钮的第一次触发
        };
        this.onBtnOperation = this.onBtnOperation.bind(this);
    }

    componentWillReceiveProps(nextprops) {
        let nextjson = JSON.stringify(nextprops.json);
        let thisjson = JSON.stringify(this.props.json);
        if (nextjson !== thisjson) {
            this.setState({
                json: nextprops.json
            })
        }
        if (nextprops.showDetail !== this.props.showDetail) {
            updateButtonStatus(nextprops);
        }
    }

    componentDidMount() {
        updateButtonStatus(this.props);
    }

    /**
     * 查询主组织 节点信息
     */
    searchChange(val) {
        if (!this.props.queryOid) {
            this.setState({
                hrorgobj: null
            });
            return
        }
        this.setState({
            hrorgobj: val
        });
        this.props.updateState({
            hrorgval: val.refpk,
            hrorgobj: val
        }, () => {
            updateButtonStatus(this.props);
            val.refpk && this.props.getLeftTreeData();
        });
    }

    /**
     * 右表是否包含在职人员
     * @param val
     */
    onCheckChange(val) {
        // 未选择人力资源资源 退出
        if (!this.props.hrorgval) return;

        this.props.updateState({
            inposFlag: val
        }, () => {
            //重新请求数据
            this.props.refresh();
        })
    }

    onBtnOperation(props, btncode, areacode, record) {
        if (areacode === 'list') {
            switch (btncode) {
                case 'query':
                    // 查询
                    let template = this.props.meta.getMeta();
                    template["psnquery"].items.map(item => {
                        if(item.itemtype === 'refer') {
                            item.queryCondition = () => {
                                return {
                                    "pk_org": this.state.hrorgobj.refpk
                                }
                            }
                        }
                        
                        // 部门
                        if (item.attrcode === 'hi_psnjob.pk_dept') {
                            item.queryCondition = () => {
                                return {
                                    'pk_hrorg': this.state.hrorgobj.refpk
                                }
                            }
                        }
                        if (item.attrcode === 'hi_psndoc_ctrt.pk_conttext') {
                            item.queryCondition = () => {
                                return {
                                    'pk_org': this.state.hrorgobj.refpk,
                                    'GridRefActionExt': "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                                }
                            }
                        }
                        // // 部门编码
                        // if (item.attrcode === 'hi_psnjob.pk_dept.code') {
                        //     item.queryCondition = () => {
                        //         return {
                        //             'pk_org': this.state.hrorgobj.refpk
                        //         }
                        //     }
                        // }
                        // 员工号
                        if (item.attrcode === 'hi_psnjob.clerkcode') {
                            item.queryCondition = () => {
                                return {
                                    'pk_org': this.state.hrorgobj.refpk,
                                    "busiregionEnum": "psnpact",
                                    "GridRefActionExt": "nccloud.web.hrcm.pub.sqlbuilder.PsndocQryRefSqlBuilder",
                                    "ismainjob": "Y"
                                    // "func_type": 4,
                                    // "GridRefActionExt": "nccloud.web.hrhi.psndoc.sqlbuilder.PsndocQryDlgPsnRefSqlBuilder"
                                }
                            }
                        }
                    });
                    this.props.meta.setMeta(template, () => {
                        this.props.search.openAdvSearch('psnquery', true);
                    });
                    break;
                case 'browse':
                    // 浏览
                    this.browseTemplet();
                    break;
                case 'contract':
                    // 合同文本
                    if (!isMac(this.props.json['cm6011-000148'])) {
                        this.contractTextView();
                    }
                    break;
                case 'sign':
                    // 合同签订
                    this.contractSign(btncode);
                    break;
                case 'change':
                    // 合同变更
                    this.contractSign(btncode);
                    break;
                case 'extend':
                    // 合同续签
                    this.contractSign(btncode);
                    break;
                case 'release':
                    // 合同解除
                    this.contractSign(btncode);
                    break;
                case 'finish':
                    // 合同终止
                    this.contractSign(btncode);
                    break;
                case 'contopinion':
                    // 续签意见征询
                    this.contractSign(btncode);
                    break;
                case 'refresh':
                    this.props.refresh(() => {
                        toast({
                            color: 'success',
                            content: this.state.json['cm6011-000006']
                        });//刷新成功！
                    });
                    break;
                case 'file':
                    this.props.updateState({
                        showUploader: true
                    });
                    break;
                case 'export':
                    //导出
                    Export(document.querySelector('.u-table-scroll'),
                        {
                            title: this.state.json['cm6011-000061'] /* 国际化处理： 合同处理中心*/,
                            fileName: this.state.json['cm6011-000102'] /* 国际化处理： 合同处理中心数据*/,
                            maker: this.state.json['cm6011-000100'] /* 国际化处理： 制单人*/,
                            date: this.state.json['cm6011-000101'] /* 国际化处理： 制表日期*/
                        }, {
                            data: this.props.editTable.getAllData(tableid).rows,
                            meta: this.props.meta.getMeta()[tableid],
                            showIndex: false
                        });
                    break;
                case 'print':
                    if (this.props.showDetail) {
                        print(
                            'pdf',
                            // 修改url
                            '/nccloud/hrcm/account/ContractBatchPrintAction.do',
                            {
                                funcode: '60110301',
                                nodekey: '6011center',
                                oids: [this.props.pk_psndoc_sub]
                            }
                        );
                    } else {
                        const el = document.querySelector('.table_print').cloneNode(true);
                        const table = el.querySelector('.u-table-content');
                        table.removeChild(table.lastElementChild);
                        const tHeader = el.querySelector('.u-table-header');
                        const tr = tHeader.querySelector('tr');
                        tr.removeChild(tr.firstElementChild);
                        tr.removeChild(tr.firstElementChild);
                        const tableTmp = this.props.meta.getMeta()[tableid];
                        do_print(
                            el,
                            {
                                title: this.state.json['cm6011-000061'] /* 国际化处理： 合同处理中心*/,
                                maker: this.state.json['cm6011-000033'] /* 国际化处理： 打印人*/,
                                date: this.state.json['cm6011-000034'] /* 国际化处理： 打印日期*/,
                                maxColLen: 11,
                                beforeAppend: (tableDataList) => {
                                    tableDataList[0][0] = this.getTableTmp(tableTmp);
                                    return tableDataList
                                }
                            },
                            {
                                tableTmp: tableTmp,
                                data: this.props.editTable.getAllRows(tableid)
                            }
                        );
                    }
                    break;
                case 'output':
                    // 点击输出按钮
                    // debugger
                    if (this.props.showDetail) {
                        // 点击输出按钮
                        output({
                            url: '/nccloud/hrcm/account/ContractBatchPrintAction.do',
                            data: {
                                funcode: '60110301',      //功能节点编码，即模板编码
                                nodekey: '6011center',     //模板节点标识
                                oids: [this.props.pk_psndoc_sub],    // 功能节点的数据主键
                                outputType: 'output',
                                filename: this.state.json['cm6011-000061'] // 输出文件名
                            },
                            callback: function () {

                            }
                        });
                    } else {
                        Export(document.querySelector('.u-table-scroll'),
                            {
                                title: this.state.json['cm6011-000061'] /* 国际化处理： 合同处理中心*/,
                                fileName: this.state.json['cm6011-000102'] /* 国际化处理： 合同处理中心数据*/,
                                maker: this.state.json['cm6011-000100'] /* 国际化处理： 制单人*/,
                                date: this.state.json['cm6011-000101'] /* 国际化处理： 制表日期*/
                            }, {
                                data: this.props.editTable.getAllData(tableid).rows,
                                meta: this.props.meta.getMeta()[tableid],
                                showIndex: false
                            });
                    }

                    break;
                default:
                    break;
            }
        } else if (areacode === 'body') {
            switch (btncode) {
                case 'contract_body':
                    // 合同文本
                    if (!isMac(this.props.json['cm6011-000148'])) {
                        this.contractTextView(record);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 合同签订
     */
    contractSign(btncode) {
        let psnjobs = this.getChecked('pk_psnjob');
        if (!psnjobs) {
            toast({
                color: 'warning',
                content: this.state.json['cm6011-000089'] // "没有选择数据！"
            });
            return
        }
        MakeCenterAction(this.props.hrorgval, psnjobs, this.props.querylast, btncode).then(async (res) => {
            let operType = res.data.operType;
            if (operType === '2') {
                let warnInf = res.data.warnInf.replace(/\n/g, "<br/>");
                this.props.updateState({
                    nextOperationVisible: true,
                    transactionModelId: btncode,
                    ctrtVOs: res.data.ctrtVOs,
                    vPks: JSON.parse(res.data.vPks),
                    pageUrl: res.data.pageUrl,
                    warnInf: warnInf
                });
                return
            }
            if (operType !== '1') {
                return
            }
            if (btncode !== 'extend') {
                this.openTransaction(btncode);
                return;
            }
            if (psnjobs.indexOf(',') === -1) {
                this.props.updateState({
                    extendtype: '0'
                }, () => {
                    this.openTransaction(btncode);
                });
                return;
            }
            this.props.updateState({
                nextOperationVisible: true,
                transactionModelId: 'extend',
                ctrtVOs: null,
                vPks: null,
                pageUrl: null,
                warnInf: this.state.json['cm6011-000118'] // "系统将按所选人员中每个人到期日期的第二天开始续签，<br/>请选择续签方式："
            });
        })
    }

    /**
     * 打开业务处理弹窗
     * @param btncode
     */
    openTransaction(btncode) {
        if (btncode === 'contopinion') {
            let psnjobs = this.getChecked('pk_psnjob');
            this.props.openOpinionAskNode(psnjobs);
        } else {
            this.props.updateState({
                transactionFormId: this.props.transactionFormId[btncode],
                transactionModelId: btncode
            }, () => {
                this.props.showTransaction();
            })
        }
    }

    /**
     * 获取选中列表的某项属性
     * @param key
     */
    getChecked(key) {
        let keys = [];
        let rows = this.props.editTable.getCheckedRows(tableid);
        if (rows.length > 0) {
            rows.map(item => {
                let values = item.data.values;
                if (values.hasOwnProperty(key)) {
                    keys.push(values[key].value);
                }
            })
        }

        let ret = keys.length > 0 ? keys.join(',') : false;
        return ret
    }

    /**
     * 获取表头
     * @param tmp
     * @returns {Array}
     */
    getTableTmp(tmp) {
        let tableTmp = [];
        let visibleCol = [];
        tmp.items.forEach((item) => {
            if (item.visible && item.attrcode !== 'opr') {
                visibleCol.push(item);
            }
        });
        visibleCol.forEach((col) => {
            tableTmp.push(col.label);
        });

        return tableTmp
    }

    /**
     * 浏览
     */
    browseTemplet() {
        BrowseTempletAction(this.props.hrorgval, this.props.pk_conmodel).then(res => {
        })
    }

    /**
     * 合同文本
     */
    contractTextView(record) {
        let that = this;
        let pk_psndoc_subs = record ? record.values.pk_psndoc_sub.value : this.props.pk_psndoc_sub;
        ContractTextViewAction(this.props.hrorgval, pk_psndoc_subs).then(res => {
            if (!res['data']) return;
            if (record) {
                nodeRefs.wpsview.openView([{data: record}], 'ct')
            } else {
                let formId = ''
                // 签订=1,续签=2,变更=3,解除=4,终止=5
                if(that.props.conttype === "1") {
                    formId = 'make';
                } else if (that.props.conttype === "2") {
                    formId = 'change';
                } else if (that.props.conttype === "3") {
                    formId = "extend"
                } else if (that.props.conttype === "4") {
                    formId = "release"
                } else if (that.props.conttype === "5") {
                    formId = "finish"
                }
                console.log(formId)
                /*获取表单所有数据*/
                let formData = that.props.form.getAllFormValue(formId).rows
                nodeRefs.wpsview.openView(formData, 'ct')
            }

            // let location = window.location;
            // location.port ? window.open("uclient://start/http://" + location.hostname + ":" + location.port + res.data) : window.open("uclient://start/http://" + location.hostname + res.data)
        })
    }

    back() {
        this.props.updateState({
            pk_psndoc_sub: null,
            showDetail: false
        })
    }

    render() {
        const {button, showDetail} = this.props;
        return (
            <div className="page-header header">
                {showDetail ? <div className={'page-header-left'}>
                    <NCBackBtn onClick={this.back.bind(this)} title={this.state.json['cm6011-000060']}/>
                    {/* 国际化处理： 返回*/}
                </div> : <div className={'page-header-left'}>
                    <div className={'leftDepartmentChoose'}>
                        {this.props.queryOid && <ReferSearch
                            orgVal={this.state.hrorgobj}
                            getOrgData={this.searchChange.bind(this)}
                            queryCondition={
                                () => {
                                    return {
                                        controlType: 0
                                    }
                                }
                            }
                        />}
                    </div>
                    {/* 标题 title*/}
                    {this.props.hrorgval && <div className="title">
                        <span className="showOff">
                            <NCCheckbox checked={this.props.inposFlag} onChange={
                                this.onCheckChange.bind(this)
                            }>{this.state.json['cm6011-000003']}</NCCheckbox>{/* 国际化处理： 在职人员 */}
                        </span>

                    </div>}
                </div>}
                {this.props.hrorgval && <div className={'page-header-right'}>
                    {button.createButtonApp({
                        area: 'list',
                        onButtonClick: (props, btncode) => {
                            this.onBtnOperation(props, btncode, 'list', this);
                        }
                    })}
                </div>}
            </div>
        );
    }
}

export default Header;
